import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Table, Tree, Button, Icon } from 'antd';
import category from '../../models/category';
import Edit from './Edit';

const TreeNode = Tree.TreeNode;

@connect(({ category, loading }) => ({
	category,
	loading: loading.models.category,
}))
class List extends PureComponent {
	state = {
		title: ''
	}

	componentDidMount() {
		this.props.dispatch({
			type: 'category/fetchCategory'
		});
	}

	componentWillUnmount() {

	}

	renderTreeNodes = (data) => {
		return data.map((item) => {
			if (item.children) {
				return (
					<TreeNode title={item.title} key={item.key} dataRef={item}>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			}
			return <TreeNode {...item} />;
		});
	}

	goAdd = () => {
		this.setState({
			title: '新增'
		})
		const { dispatch } = this.props;
		dispatch({
			type: 'category/changeEdit'
		})

	}

	render() {
		let { modal, list } = this.props.category;
		let { title } = this.state;
		return (<div style={{ background: '#ECECEC', padding: '30px' }}>
			<Card title="分类管理" bordered={false}>
				<Button type="primary" onClick={this.goAdd}><Icon type="file-add" /> 新增</Button>
				<Edit visible={modal} title={title || '编辑'} />
				<Tree>
					{this.renderTreeNodes(list)}
				</Tree>
			</Card>
		</div>);
	}
}

export default List;